package com.inspur.edp.bef.bemanager;


import com.inspur.edp.bef.bemanager.i18nservice.BizEntityI18nService;
import com.inspur.edp.bef.bemanager.util.DboUtil;
import com.inspur.edp.bef.bemanager.validate.BizEntityValidater;
import com.inspur.edp.bef.bizentity.GspBusinessEntity;
import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.entity.MetadataHeader;
import com.inspur.edp.lcm.metadata.api.entity.MetadataReference;
import com.inspur.edp.lcm.metadata.api.service.MetadataService;
import com.inspur.edp.lcm.metadata.spi.event.MetadataEventArgs;
import com.inspur.edp.lcm.metadata.spi.event.MetadataEventListener;
import com.inspur.edp.wf.bizprocess.entity.FlowFormEntity;
import com.inspur.edp.wf.bizprocess.rest.FlowFormServiceImpl;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;

import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BeMetadataEventListener implements MetadataEventListener {
    /**
     * 业务实体元数据保存前事件
     *
     * @param
     */

    private Logger logger = LoggerFactory.getLogger(BeMetadataEventListener.class);
    private  FlowFormServiceImpl flowFormService;

    private final FlowFormServiceImpl getFlowFormServiceImpl () {
        if(this.flowFormService == null) {
            this.flowFormService = SpringBeanUtils.getBean(FlowFormServiceImpl.class);
        }
        return this.flowFormService;
    }


    public final void metadataSaving(MetadataEventArgs e) {
        try {
            // 类型判断
            if (!(e.getMetadata().getContent() instanceof GspBusinessEntity)) {
                return;
            }
            GspBusinessEntity be = (GspBusinessEntity) ((e.getMetadata().getContent() instanceof GspBusinessEntity) ? e.getMetadata().getContent() : null);
            String path = e.getPath();

            //保存前校验
            BizEntityValidater validator = new BizEntityValidater();
            validator.validate(be, path);
            //国际化抽取
            BizEntityI18nService service = new BizEntityI18nService();
            service.getResourceItem(e.getMetadata());

            //20190326-依赖关系由lcm统一调用
            //MetadataReferenceService.BuildMetadataReference(e.Metadata);
            ////生成构件元数据
            //ComponentGenerator.Instance.generateComponent(be, e.Path);

            ////生成构件代码
            //new CodeFileGenerator(e.Metadata).Generate();

            ////生成/修改数据库对象
            //DboGenerater dboGenerater = new DboGenerater();
            //dboGenerater.GenerateDboFromBizEntity(be, path);
        } catch (RuntimeException exception) {
            WriteLog("be元数据保存前异常", exception);
            throw exception;
        }
    }

    private void WriteLog(String message, RuntimeException exception) {
//		String loggerName = "GspBefLogger";
        logger.error(message, exception);
    }

    @Override
    public void fireMetadataSavingEvent(MetadataEventArgs metadataEventArgs) {
        metadataSaving(metadataEventArgs);
    }

    @Override
    public void fireMetadataSavedEvent(MetadataEventArgs metadataEventArgs) {

    }

    @Override
    public void fireMetadataDeletingEvent(MetadataEventArgs metadataEventArgs) {
        if (metadataEventArgs == null) {
            return;
        }
        boolean isBe = "GSPBusinessEntity".equals(metadataEventArgs.getMetadata().getHeader().getType());
        if (!isBe) {
            return;
        }
        String path = metadataEventArgs.getPath();
        MetadataService metadataService = SpringBeanUtils.getBean(MetadataService.class);
        GspMetadata metadata = metadataService.loadMetadata(path);
        if (metadata == null) {
            return;
        }
        GspBusinessEntity be = (GspBusinessEntity) metadata.getContent();
        List<String> dboIDs = DboUtil.getDboIDs(be);
        // 删除dbo文件
        DboUtil.dealDboFiles(dboIDs, path);
    }

    @Override
    public void fireMetadataDeletedEvent(MetadataEventArgs metadataEventArgs) {
        deleteFlowFormByBizEntityId(metadataEventArgs.getMetadata().getHeader().getId());

        deleteBeResFile(metadataEventArgs);
    }

    private void deleteBeResFile(MetadataEventArgs metadataEventArgs) {
        boolean isBe = "GSPBusinessEntity".equals(metadataEventArgs.getMetadata().getHeader().getType());
        if (!isBe) {
            return;
        }
        MetadataService metadataService = SpringBeanUtils.getBean(MetadataService.class);
        GspMetadata metadata = metadataEventArgs.getMetadata();
        if (metadata == null) {
            return;
        }
        // 删除res资源
        String resMetaDataId = "";
        if(metadata.getRefs()!=null) {
            for (MetadataReference reference : metadata.getRefs()) {
                if (reference.getDependentMetadata().getType().equals("ResourceMetadata")) {
                    resMetaDataId = reference.getDependentMetadata().getId();
                    break;
                }
            }
        }
        if (resMetaDataId.isEmpty()) {
            return;
        }
        GspMetadata resMetaData = metadataService.loadMetadataByMetadataId(resMetaDataId, metadata.getRelativePath());
        String resPath = resMetaData.getRelativePath();
        String resFileName = resMetaData.getHeader().getFileName();
        metadataService.deleteMetadata(resPath, resFileName);
    }

    private void  deleteFlowFormByBizEntityId(String beId) {
        FlowFormServiceImpl serviceImpl = getFlowFormServiceImpl();
        List<FlowFormEntity> formFormEntityList = serviceImpl.getFlowFormListByBEId(beId);

        if(formFormEntityList == null || formFormEntityList.size() == 0) {
            // 当前BE没有映射的工作流
            return;
        }
        formFormEntityList.forEach(ele -> serviceImpl.delete(ele.getId()));
    }

}
